package net.maxwoods.nimble.websocket;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import java.util.Collection;

public class WebSocketHandler extends IoHandlerAdapter {

    @Override
    public void exceptionCaught(IoSession session, Throwable cause)
            throws Exception {
        super.exceptionCaught(session, cause);
    }

    @Override
    public void messageReceived(IoSession session, Object message)
            throws Exception {
        MinaBean minaBean = (MinaBean) message;
        if (minaBean.isWebAccept()) {
            MinaBean sendMessage = minaBean;
            sendMessage.setContent(WebSocketUtil.getSecWebSocketAccept(minaBean
                    .getContent()));
            session.write(sendMessage);
        } else {
            Collection<IoSession> ioSessionSet = session.getService()
                    .getManagedSessions().values();
            for (IoSession is : ioSessionSet) {
                is.write(message);
            }
        }
    }

    @Override
    public void messageSent(IoSession session, Object message) throws Exception {
        super.messageSent(session, message);
    }

    @Override
    public void sessionClosed(IoSession session) throws Exception {
        super.sessionClosed(session);
    }

    @Override
    public void sessionCreated(IoSession session) throws Exception {
        super.sessionCreated(session);
    }

    @Override
    public void sessionIdle(IoSession session, IdleStatus status)
            throws Exception {
        super.sessionIdle(session, status);
        session.close(false);
    }

    @Override
    public void sessionOpened(IoSession session) throws Exception {
        super.sessionOpened(session);
    }
}
